(function (PDFAPI, window, document, undefined) {
  // 任务队列
  var execTaskQueue = [];
  //iframe 是否可用
  var iframeIsReady = false;

  PDFAPI.DocEditor = function (placeholderId, config) {
    var _config = config || {};

    extend(_config, PDFAPI.DocEditor.defaultConfig);

    var target = document.getElementById(placeholderId),
      iframe;

    if (target) {
      iframe = createIframe(_config);
      target.parentNode && target.parentNode.replaceChild(iframe, target);

      _exec({
        method: "init",
        data: config,
      });
    }

    function createIframe(config) {
      var iframe = document.createElement("iframe");

      iframe.src = getAppPath(config) + getAppParameters(config);
      iframe.width = config.width;
      iframe.height = config.height;
      iframe.align = "top";
      iframe.frameBorder = 0;
      iframe.name = "frameEditor";
      iframe.onload = function () {
        iframeIsReady = true;
        while (execTaskQueue.length) {
          _exec(execTaskQueue.shift());
        }
      };
      return iframe;
    }

    function _exec({ method, data = {} } = {}) {
      if (iframeIsReady) {
        postMessage(iframe.contentWindow, {
          method,
          data,
        });
      } else {
        execTaskQueue.push({
          method,
          data,
        });
      }
    }

    return {
      exec: _exec,
    };
  };

  //默认值
  PDFAPI.DocEditor.defaultConfig = {
    width: "100%",
    height: "100%",
  };

  PDFAPI.DocEditor.version = function () {
    return "1.0.0";
  };

  function getAppPath(config) {
    // if (/localhost|(127.0.0.1)/.test(location.href)) {
    //   开发
    //   return "http://localhost:8858/web/viewer.html";
    // } else {window.location.origin
    // return decodeURI(location.href.replace('/index.html', '')) + `/generic-legacy/web/viewer.html`;
    return decodeURI(window.location.origin) + `/generic-legacy/web/viewer.html`;
    // }
  }

  function getAppParameters(config) {
    var params = "?t=" + +new Date();
    return params;
  }

  function postMessage(wnd, msg) {
    if (wnd && wnd.postMessage && window.JSON) {
      wnd.postMessage(window.JSON.stringify(msg), "*");
    }
  }

  function extend(dest, src) {
    for (var prop in src) {
      if (src.hasOwnProperty(prop)) {
        if (typeof dest[prop] === "undefined") {
          dest[prop] = src[prop];
        } else if (
          typeof dest[prop] === "object" &&
          typeof src[prop] === "object"
        ) {
          extend(dest[prop], src[prop]);
        }
      }
    }
    return dest;
  }
})((window.PDFAPI = window.PDFAPI || {}), window, document);
